<?php

require_once(DIR_LIB."VsShop".DIR_SEP."vscustomer.php");

require_once(DIR_LIB."VsShop".DIR_SEP."vsorderaddress.php");

require_once(DIR_LIB."VsShop".DIR_SEP."vsorderitem.php");

require_once(DIR_LIB."VsShop".DIR_SEP."vsorderstatus.php");

class VsOrder {

	static function makeOrders() {	// Vremenno Izpalnenie
		$orders = array();

		$db = VsDatabase::Instance();
		$q = "SELECT id FROM `orders`";
		$res = $db->query($q);
		while($rOrder = mysql_fetch_object($res)) {
			array_push($orders, new VsOrder($rOrder->id));
		}

		return $orders;
	}
	//================================================================================================

	protected $_sqlTable = '';
	protected $_db = NULL;

	protected $_sessionId = 0;

	protected $_id = 0;

	protected $_customer = NULL;

	protected $_paymentMethod = '';
	protected $_shippingMethod = '';

	protected $_billingAddress = NULL;
	protected $_shippingAddress = NULL;

	protected $_orderItems = array();

	protected $_date = NULL;
	protected $_status = NULL;

	protected $_total = 0;
	protected $_shippingPrice = 0;

	function __construct($id=0) {
		$this->_sqlTable = 'orders';
		$this->_db = VsDatabase::Instance();

		if($id) {
			$db = VsDatabase::Instance();
			$q = "SELECT * FROM `orders` WHERE id=".$id;

			$res = $db->query($q);
			$order = mysql_fetch_object($res);

			$this->_sessionId = $order->session_id;
			$this->_id = $order->id;
			$this->_customer = new VsCustomer($order->customers_id);

			//$q = "SELECT * FROM `orders_items` WHERE orders_id=".$id;
			//$res = $db->query($q);
			$this->_orderItems = VsOrderItemFactory::makeOrderItems($id);

			$this->initAddresses();
			$this->_status = new VsOrderStatus($order->status);

			$this->_paymentMethod = $order->payment_method;
			$this->_shippingMethod = $order->shipping_method;
		}
		else {
			$this->_sessionId = VsSession::Instance()->id();
			$this->_status = new VsOrderStatus;

			$this->_billingAddress = VsOrderAddress::makeNewBilling($this);

			//echo $this->_billingAddress ? "Billing Address Initialized" : "Billing Address Not Initialized";
			//exit;
		}
	}
	//=====================================================================

	function availableStatuses() { return VsOrderStatus::$AvailableStatuses; }
	function statuses() { return VsOrderStatus::AvailableStatuses(); }
	function status() { return $this->_status; }
	function statusKey() {return $this->_status->key();}
	function statusValue() {return $this->_status->value();}

	function id() { return $this->_id; }
	function orderId() { $this->_order->id(); }

	function billingAddress() { return $this->_billingAddress; }
	function shippingAddress() { return $this->_shippingAddress; }

	function items() { return $this->_orderItems; }
	function date() { return $this->_date; }

	function addTotal($total) { $this->_total += $total; }
	function total() { return $this->_total; }
	function shippingPrice() { return $this->_shippingPrice; }
	function grossTotal() { return $this->_total + $this->_shippingPrice; }
	//=========================================================================================================================

	function paymentMethod() { return $this->_paymentMethod; }
	function shippingMethod() { return $this->_shippingMethod; }
	//=========================================================================================================================================

	function customer() { return $this->_customer; }
	function customerName() { return $this->_billingAddress ? $this->_billingAddress->firstName()." ".$this->_billingAddress->lastName() : '<span style="color:red;">Billing Address Not Defined</span>'; }
	function firstName() { return $this->_billingAddress ? $this->_billingAddress->firstName() : '<span style="color:red;">Billing Address Not Defined</span>'; }
	function lastName() { return $this->_billingAddress ? $this->_billingAddress->lastName() : '<span style="color:red;">Billing Address Not Defined</span>'; }
	function mail() { return $this->_billingAddress ? $this->_billingAddress->mail() : '<span style="color:red;">Billing Address Not Defined</span>'; }
	function phone() { return $this->_billingAddress ? $this->_billingAddress->phone() : '<span style="color:red;">Billing Address Not Defined</span>'; }
	function address() { return $this->_billingAddress->address(); }
	function city() { return $this->_billingAddress->city(); }
	function postCode() { return $this->_billingAddress->postCode(); }
	function province() { return $this->_billingAddress->province(); }
	function country() { return $this->_billingAddress->country(); }

	//===============================================================================================================================================

	function shipFirstName() { return $this->_shippingAddress ? $this->_shippingAddress->firstName() : $this->_billingAddress->firstName(); }
	function shipLastName() { return $this->_shippingAddress ? $this->_shippingAddress->lastName() : $this->_billingAddress->lastName(); }
	function shipPhone() { return $this->_shippingAddress ? $this->_shippingAddress->phone() : $this->_billingAddress->phone(); }
	function shipAddress() { return $this->_shippingAddress ? $this->_shippingAddress->address() : $this->_billingAddress->address(); }
	function shipCity() { return $this->_shippingAddress ? $this->_shippingAddress->city() : $this->_billingAddress->city(); }
	function shipPostCode() { return $this->_shippingAddress ? $this->_shippingAddress->postCode() : $this->_billingAddress->postCode(); }
	function shipProvince() { return $this->_shippingAddress ? $this->_shippingAddress->province() : $this->_billingAddress->province(); }
	function shipCountry() { return $this->_shippingAddress ? $this->_shippingAddress->country() : $this->_billingAddress->country(); }
	//============================================================================================================================================

	function addItem($productId, $qty) {
		//echo "VsShoppingCart::addItem(productId, qty)";

		foreach($this->_orderItems as $item) {
			if($item->id() == $productId) {
				$item->addQty($qty);
				return;
			}
		}

		array_push($this->_orderItems, new VsOrderItem($this, $productId, $qty));
	}
	//=========================================================================================

	function removeItem($id) {
		if(!$this->_id) {
			if(array_key_exists($id, $this->_orderItems)) {
				array_splice($this->_orderItems, $id, 1);
				return TRUE;
			}
		}
		else {
			foreach($this->_orderItems as $key => $item) {
				if($item->id() == $id) {
					if($item->delete()) {
						array_splice($this->_orderItems, $key, 1);
						return TRUE;
					}
				}
			}
		}

		return FALSE;
	}
	//=========================================================================================

	function setPaymentMethod($payMethod) {
		$this->_paymentMethod =  $payMethod; 
	}
	//=========================================================================================

	function setShippingMethod($shipMethod) {
		$this->_shippingMethod =  $shipMethod;
	}
	//=========================================================================================

	function setAddresses($formArray) {

	}
	//========================================================================

	function setBillingAddress($formArray) {
		$this->_billingAddress = VsOrderAddress::makeFromUser($this, $formArray);
	}
	//=========================================================================

	function setShippingAddress($formArray) {
		$this->_shippingAddress = VsOrderAddress::makeFromUser($this, $formArray);
	}
	//=========================================================================

	function save() {
		//echo "VsProduct::save()";

		if($this->_id > 0)
			$this->update();
		else
			$this->insert();


		foreach($this->_orderItems as $item)
			$item->save();

		if($this->_billingAddress)
			$this->_billingAddress->save();

		if($this->_shippingAddress)
			$this->_shippingAddress->save();
	}
	//=========================================================================================

	function delete() {
		$q = "DELETE FROM `".$this->_sqlTable."` WHERE id=".$this->_id;

		$this->_db->query($q);
	}
	//========================================================================================

	function updateStatus($status) {
		if(!$this->_status->setStatus($status))
			return FALSE;

		$db = VsDatabase::Instance();
		$q = "UPDATE `".$this->_sqlTable."` SET `status`=".$this->_status->key()." WHERE id=".$this->_id;
		$db->query($q);

		//echo $q;
		//exit;

		return TRUE;
	}
	//==========================================================================================

	protected function initAddresses() {
		if(!$this->_id)
			return;

		$db = VsDatabase::Instance();

		$q = "SELECT id, type FROM `order_addresses` WHERE order_id=".$this->_id;
		$res = $db->query($q);
		while($addr = mysql_fetch_object($res)) {
			if($addr->type == 'billing') {
				$this->_billingAddress = VsOrderAddress::makeFromDb($this, $addr->id);

			}
			else if($addr->type == 'shipping') {
				$this->_shippingAddress = VsOrderAddress::makeFromDb($this, $addr->id);

			}	
		}
	}
	//============================================================================

	protected function insert() {
		$db = VsDatabase::Instance();

		$q = "INSERT INTO `".$this->_sqlTable."` (`session_id`, `payment_method`, `shipping_method`, `date`, `status`) VALUES('".$this->_sessionId."', '".$this->_paymentMethod."', '".$this->_shippingMethod."', NOW(), '".$this->_status->key()."')";
		//echo $q;

		$db->query($q);
		//echo mysql_error();

		$this->_id = mysql_insert_id();
	}
	//=========================================================================================================

	protected function update() {
		/*
		$q = "UPDATE `".$this->_sqlTable."` SET `products_id`='".$this->_productColor->productId()."', `name`='".addslashes($this->_name)."', `info`='".addslashes($this->_info)."', date=NOW() WHERE id=".$this->_id;

		$this->_db->query($q);
		*/
	}
	//========================================================================================================


};

?>
